package com.keepers.repair.fragment


import android.content.Context
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.keepers.repair.R
import com.keepers.repair.activity.BaseActivity
import com.keepers.repair.adapter.UserAdapter
import com.keepers.repair.helper.SpHelper
import com.keepers.repair.model.UserModel
import com.keepers.repair.utils.Api
import com.keepers.repair.view.TitleBar
import org.jetbrains.anko.find

class MainGroupFragment : BaseFragment() {

    private lateinit var refreshLayout: SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var titleBar: TitleBar
    private lateinit var loginUserInfo : UserModel
    private var userList = mutableListOf<UserModel>()

    private var isImmersiveStatusBar: Boolean = false

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        if (context is BaseActivity) {
            this.isImmersiveStatusBar = context.isImmersiveStatusBar
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_main_group, container, false)

        if (isImmersiveStatusBar) {
            f<View>(view, R.id.status_bar).visibility = View.VISIBLE
        }
        titleBar = view.find(R.id.title_bar)
        loginUserInfo = SpHelper.getLoginUserInfo()
        titleBar.initializeHeader(loginUserInfo.GroupName)
        refreshLayout = view.find(R.id.signed_refresh_layout)
        recyclerView = view.find(R.id.signed_recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = UserAdapter(userList)
        refreshLayout.setOnRefreshListener(this::refreshList)
        refreshList()
        return view
    }

    private fun refreshList() {
        loginUserInfo.apply {
            refreshLayout.isRefreshing = true
            Api.getUserList(this.GroupGid!!) { list ->
                userList.clear()
                list.forEach { userList.add(it) }
                recyclerView.adapter?.notifyDataSetChanged()
                refreshLayout.isRefreshing = false
            }
        }
    }
}
